package com.atguigu.eduservice.controller;


import com.atguigu.commonutils.R;
import com.atguigu.eduservice.client.VodClient;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.service.EduVideoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author dujiajia
 * @since 2020-11-03
 */
@RestController
@RequestMapping("/eduservice/video")
@Api(tags = "课程小节管理")
//@CrossOrigin
public class EduVideoController {

    @Autowired
    private EduVideoService eduVideoService;
    // 调用其他微服务的方法， 注入
    @Autowired
    private VodClient vodClient;


    @ApiOperation("添加小节")
    @PostMapping("addVideo")
    public R addVideo(@RequestBody EduVideo eduVideo) {
        boolean save = eduVideoService.save(eduVideo);
        if (save) {
            return R.ok();
        }else {
            return R.error();
        }
    }
    @ApiOperation("更新小节")
    @PutMapping("updateVideo")
    public R updateVideo(@RequestBody EduVideo eduVideo) {
        boolean update = eduVideoService.updateById(eduVideo);
        if (update) {
            return R.ok();
        }else {
            return R.error();
        }
    }

    @ApiOperation("删除小节")
    @DeleteMapping("deleteVideo/{id}")
    public R deleteVideo(@PathVariable String id) {

        EduVideo eduVideo = eduVideoService.getById(id);
        String videoSourceId = eduVideo.getVideoSourceId();
        // 删除小节之前先删除视频 传入视频的Id
        // 判断小节是否有视频id 如果有视频才删除
        if(!StringUtils.isEmpty(videoSourceId)){
            vodClient.removeAlyVideo(videoSourceId);
        }
        // 后删除小节
        boolean b = eduVideoService.removeById(id);
        if (b){
            return R.ok();
        }else {
            return R.error();
        }
    }
    @ApiOperation("根据id查询小节")
    @GetMapping("getVideo/{id}")
    public R getVideo(@PathVariable String id) {

        EduVideo eduVideo = eduVideoService.getById(id);
        return R.ok().data("eduVideo",eduVideo);
    }

}

